package br.com.ps.bombertournament.game.object;

import java.util.ArrayList;
import java.util.List;

import br.com.ps.bombertournament.game.BaseGameObject;
import br.com.ps.bombertournament.game.MappedGameObject;
import br.com.ps.bombertournament.game.action.TranslateAction;
import br.com.ps.bombertournament.game.animation.Action;
import br.com.ps.bombertournament.game.animation.AnimationGameObject;

public class Player extends MappedGameObject {

	private String configurations;
	private boolean death;
	
	private int power = 2;
	private int maxBombs = 1;
	
	private List<Bomb> bombs = new ArrayList<Bomb>();
	
	public enum Keyboard {
		RIGHT,
		LEFT,
		UP,
		DOWN,
		SPACE
	}
	
	public Player() {}
	
	public Player(String configurations) {
		this.configurations = configurations;
	}
	
	@Override
	public String getMapPath() {
		return configurations != null ? configurations : super.getConfigurations().getString(MappedGameObject.CONFIGURATIONS_PROPERTY);
	}
	
	@Override
	public void onRemove() {
		// Do nothing
	}

	@Override
	public void onCollision(BaseGameObject other) {
		if (death) {
			return;
		}
		
		if (other instanceof SuperWall) {
			if (super.currentAnimation != null) {
				for (Action action : super.currentAnimation.getCurrentFrame().getActions()) {
					if (action instanceof TranslateAction) {
						action.undo(this);
						super.stop();
						
						return;
					}
				}
			}
		} else if (other instanceof BombFire && death == false) {
			death = true;
			super.play("DIE");
		}
	}
	
	@Override
	public boolean play(String animation) {
		boolean result = this.animations.containsKey(animation);
		
		if (result) {
			AnimationGameObject tempAnimationGameObject = this.animations.get(animation);
			
			if (tempAnimationGameObject != currentAnimation) {
				this.currentAnimation = this.animations.get(animation);
				this.currentAnimation.reset();
			} else {
				if (this.currentAnimation.isFinished()) {
					this.currentAnimation.reset();
				}
			}
		}
		
		return result;
	}
	
	public boolean processEvent(Keyboard keyboard) {
		boolean result = false;
		
		switch(keyboard) {
			case UP:
				play("WALK_UP");
				
				result = true;
			break;
			
			case DOWN:
				play("WALK_DOWN");
				
				result = true;
			break;
			
			case RIGHT:
				play("WALK_RIGHT");
				
				result = true;
			break;
			
			case LEFT:
				play("WALK_LEFT");
				
				result = true;
			break;
			
			case SPACE:
				
				for (int i = 0; i < bombs.size(); i++) {
					if (bombs.get(i).isOnScene() == false) {
						bombs.remove(i--);
					}
				}
				
				if (bombs.size() < maxBombs) {
					Bomb bomb = FactoryGameObject.createBomb(power);
					bomb.setPosition(super.getX(), super.getY());

					super.getLayer().add(bomb);
					bombs.add(bomb);
					
					result = true;
				}
			break;
		}
		
		return result;
	}
}
